<!--
  余额变动记录组件
  @description 查看商户余额的变动记录
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1000px"
    :scroll="true"
    max-height="600px"
  >
    <div v-loading="loading">
      <!-- 余额信息展示 -->
      <el-card class="mb-20px" v-if="balanceData">
        <template #header>
          <div class="card-header">
            <span>{{ t('settle.balance.balanceInfo') }}</span>
          </div>
        </template>
        <el-descriptions :column="4" border>
          <el-descriptions-item :label="t('settle.balance.merchantNo')">
            {{ balanceData.merchantNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.balance.merchantName')">
            {{ balanceData.merchantName }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.balance.availableBalance')">
            <span class="available-text"
              >¥{{ (balanceData.availableBalance / 100).toFixed(2) }}</span
            >
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.balance.frozenBalance')">
            <span class="frozen-text">¥{{ (balanceData.frozenBalance / 100).toFixed(2) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 搜索表单 -->
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        label-width="80px"
        class="mb-20px"
      >
        <el-form-item :label="t('settle.balance.changeType')" prop="changeType">
          <el-select
            v-model="queryParams.changeType"
            :placeholder="t('settle.common.pleaseSelect') + t('settle.balance.changeType')"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(label, value) in changeTypeOptions"
              :key="value"
              :label="label"
              :value="parseInt(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('settle.balance.changeTime')" prop="changeTime">
          <el-date-picker
            v-model="queryParams.changeTime"
            type="datetimerange"
            range-separator="-"
            :start-placeholder="t('settle.common.startTime')"
            :end-placeholder="t('settle.common.endTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            {{ t('settle.common.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            {{ t('settle.common.reset') }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 变动记录列表 -->
      <el-table :data="recordList" row-key="id" v-loading="recordLoading">
        <el-table-column
          :label="t('settle.balance.changeType')"
          align="center"
          prop="changeType"
          width="120"
        >
          <template #default="scope">
            <el-tag :type="getChangeTypeTagType(scope.row.changeType)">
              {{ changeTypeOptions[scope.row.changeType] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('settle.balance.changeAmount')"
          align="center"
          prop="changeAmount"
          width="120"
        >
          <template #default="scope">
            <span :class="scope.row.changeAmount > 0 ? 'increase-text' : 'decrease-text'">
              {{ scope.row.changeAmount > 0 ? '+' : '' }}¥{{
                (scope.row.changeAmount / 100).toFixed(2)
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('settle.balance.balanceBefore')"
          align="center"
          prop="balanceBefore"
          width="120"
        >
          <template #default="scope"> ¥{{ (scope.row.balanceBefore / 100).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column
          :label="t('settle.balance.balanceAfter')"
          align="center"
          prop="balanceAfter"
          width="120"
        >
          <template #default="scope"> ¥{{ (scope.row.balanceAfter / 100).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column
          :label="t('settle.balance.relatedOrderNo')"
          align="center"
          prop="relatedOrderNo"
          width="180"
        />
        <el-table-column
          :label="t('settle.balance.changeReason')"
          align="center"
          prop="changeReason"
          min-width="200"
        />
        <el-table-column
          :label="t('settle.balance.changeTime')"
          align="center"
          prop="changeTime"
          width="180"
          :formatter="dateFormatter"
        />
      </el-table>

      <!-- 分页 -->
      <Pagination
        :total="recordTotal"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getRecordList"
        class="mt-20px"
      />
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { getBalanceChangePageApi } from '@/api/settle/balance'
import type {
  BalanceVO,
  BalanceChangeRecordVO,
  BalanceChangeRecordPageReqVO
} from '@/api/settle/types'
import { BalanceChangeTypeEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'

defineOptions({ name: 'BalanceChangeRecords' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)
const recordLoading = ref(false)

// 余额数据
const balanceData = ref<BalanceVO>()

// 记录列表数据
const recordList = ref<BalanceChangeRecordVO[]>([])
const recordTotal = ref(0)

// 查询参数
const queryParams = reactive<BalanceChangeRecordPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  merchantNo: '',
  changeType: undefined,
  changeTime: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()

// 选项数据
const changeTypeOptions = {
  [BalanceChangeTypeEnum.PAYMENT]: t('settle.balance.changeTypes.payment'),
  [BalanceChangeTypeEnum.REFUND]: t('settle.balance.changeTypes.refund'),
  [BalanceChangeTypeEnum.SETTLE]: t('settle.balance.changeTypes.settle'),
  [BalanceChangeTypeEnum.WITHDRAW]: t('settle.balance.changeTypes.withdraw'),
  [BalanceChangeTypeEnum.FREEZE]: t('settle.balance.changeTypes.freeze'),
  [BalanceChangeTypeEnum.UNFREEZE]: t('settle.balance.changeTypes.unfreeze'),
  [BalanceChangeTypeEnum.ADJUST]: t('settle.balance.changeTypes.adjust')
}

/**
 * 打开对话框
 */
const open = (balance: BalanceVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('settle.balance.changeRecords') + ' - ' + balance.merchantName
  balanceData.value = balance

  // 重置查询参数
  queryParams.merchantNo = balance.merchantNo
  queryParams.pageNo = 1
  queryParams.changeType = undefined
  queryParams.changeTime = undefined

  getRecordList()
}

/**
 * 查询变动记录列表
 */
const getRecordList = async () => {
  recordLoading.value = true
  try {
    const data = await getBalanceChangePageApi(queryParams)
    recordList.value = data.list
    recordTotal.value = data.total
  } catch (error) {
    console.error('查询余额变动记录失败:', error)
  } finally {
    recordLoading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getRecordList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryParams.changeType = undefined
  queryParams.changeTime = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 标签类型获取函数
const getChangeTypeTagType = (type: number) => {
  const typeMap = {
    [BalanceChangeTypeEnum.PAYMENT]: 'success',
    [BalanceChangeTypeEnum.REFUND]: 'warning',
    [BalanceChangeTypeEnum.SETTLE]: 'primary',
    [BalanceChangeTypeEnum.WITHDRAW]: 'info',
    [BalanceChangeTypeEnum.FREEZE]: 'danger',
    [BalanceChangeTypeEnum.UNFREEZE]: 'success',
    [BalanceChangeTypeEnum.ADJUST]: 'warning'
  }
  return typeMap[type] || ''
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.mt-20px {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.available-text {
  color: #67c23a;
  font-weight: bold;
}

.frozen-text {
  color: #e6a23c;
  font-weight: bold;
}

.increase-text {
  color: #67c23a;
  font-weight: bold;
}

.decrease-text {
  color: #f56c6c;
  font-weight: bold;
}
</style>
